package com.fw.system.web.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.common.AliComm;
import com.fw.common.IdXD;
import com.fw.enums.LogsModelEnum;
import com.fw.enums.LogsTypeEnum;
import com.fw.enums.OrderState;
import com.fw.mes.Result;
import com.fw.system.web.dao.FwAddrsMapper;
import com.fw.system.web.dao.FwSkuMapper;
import com.fw.system.web.dao.FwSpuMapper;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.dao.FwOrderMapper;
import com.fw.system.web.model.vo.AddrsVo;
import com.fw.system.web.model.vo.v2.OrderMoneyVo;
import com.fw.system.web.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fw.utils.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static com.fw.mes.ResultUtils.success;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author
 * @since 2021-05-10
 */
@Service
@Log4j2
public class FwOrderServiceImpl extends ServiceImpl<FwOrderMapper, FwOrder> implements IFwOrderService {
    @Autowired
    private IFwSpuService spuService;
    @Autowired
    private IFwSkuService skuService;
    @Autowired
    private IFwShopService shopService;
    @Autowired
    private IFwAddrsService addrsService;
    @Autowired
    private AliComm aliComm;
    @Autowired
    private IFwUserService userService;


    @Autowired
    private FwOrderMapper orderMapper;

    @Autowired
    private IFwMsgService msgService;

    @Autowired
    private IFwMoneysService moneysService;

    @Autowired
    private IFwLogsService logsService;

    @Autowired
    private IdXD idXD;
    /**
     * @Effect 完善订单
     * @Author 姚
     * @Date 2021/6/16
     */
    @Override
    public FwOrder perfectOrder(FwOrder order) {
        order.setFwSpu(spuService.getById(order.getSpuId()));
        order.setFwSku(skuService.getById(order.getSkuId()));
        AddrsVo addrsVo = addrsService.getVoById(order.getAddrId());
        if (addrsVo !=null)
            order.setFwAddr(addrsVo);
        order.setFwShop(shopService.getById(order.getShopId()) );
        return order;
    }

    /**
     * 给商户钱(返回值为null则正常成功)
     *
     * @return void
     * @author 姚自强
     * @date 2021/8/7
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public String payToShop(FwOrder order, String shopId) {

        FwShop shop = shopService.getById(shopId);
        if (shop == null) {
            log.error("订单号"+ order.getId() +"为商户付款时商铺不存在，商铺ID=>"+shopId);
            return "订单号"+ order.getId() +"为商户付款时商铺不存在，商铺ID=>"+shopId;
        }
        FwUser user = userService.getById(shop.getUserId());
        if (user == null) {
            log.error("订单号"+ order.getId() +"为商户付款时商户不存在，商户ID=>"+shop.getUserId());
            return "订单号"+ order.getId() +"为商户付款时商户不存在，商户ID=>"+shop.getUserId();
        }

        //计算给多少钱 支付的是 sku 拿 spu 原价去 * 数量？ 严重bug
 /*       FwSpu spu = spuService.getById(order.getSpuId());
        BigDecimal shopMoney = spu.getRealPrice().subtract( spu.getPrice() ).multiply( BigDecimal.valueOf(order.getSpuNumber()) );
*/
        FwSpu fwSpu = spuService.getById(order.getSpuId());
        FwSku fwSku = skuService.getById(order.getSkuId());
        BigDecimal shopMoney = fwSku.getSkuMoney().subtract(fwSpu.getPrice()).multiply(NumberUtil.add(order.getSpuNumber()));
        try {
            aliComm.aliTransfer(user.getAliPhone(), shopMoney, user.getAliUserName());
        } catch (AlipayApiException e) {
//            e.printStackTrace();
            return e.getMessage();
        }

        return null;
    }

    @Override
    public List<OrderMoneyVo> manageOnlineOrder(String shopId, Integer queryRange, Integer limit) {
        return orderMapper.manageOnlineOrder(shopId,queryRange,limit);
    }

    /**
     * 提醒发货操作
     * @param id
     * @param user
     */
    @Override
    public void pubPackage(String id, FwUser user) {
        // 将订单得 商铺号拿到
        FwOrder fwOrder = getById(id);
        Assert.isTrue(OrderState.TO_BE_DELIVERED.getCode().equals(fwOrder.getStatus()),"当前订单状态不是 待发货!");
        // 是否有用户得催单情况
        FwMsg fwMsg = msgService.getOne(Wrappers.<FwMsg>lambdaQuery().eq(FwMsg::getCreateBy, user.getId()).orderByDesc(FwMsg::getCreateTime).last(" limit 1 "));
        if (Objects.nonNull(fwMsg) && LocalDateTime.now().compareTo(fwMsg.getCreateTime().plusMinutes(5)) >=0 ){
            FwMsg msg = new FwMsg();
            msg.setId(idXD.nextId());
            msg.setTitle("您有新的催发货消息了~");
            msg.setIsRead(Integer.valueOf(0));
            msg.createD(user.getId());
            msg.setUserId(fwOrder.getShopId());
            msg.setContent(String.format("订单号为:%s , 被客户催单了,请您尽快安排发货!",id));
            msg.insert();
        }else{
            Assert.isTrue(Boolean.FALSE,"订单刚刚已经催过了,5分钟内 不可重复催单~");
        }


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> confirmReceipt(String orderId) {
        FwOrder order = getById(orderId);
        FwSpu spu = spuService.getById(order.getSpuId());
        FwShop shop = shopService.getById(spu.getShopId());
        BigDecimal shopDisappear = spu.getPrice().multiply( BigDecimal.valueOf(order.getSpuNumber()) ).setScale(2, BigDecimal.ROUND_DOWN);
        BigDecimal userDisappear = spu.getDisappear().multiply( BigDecimal.valueOf(order.getSpuNumber()) ).setScale(2, BigDecimal.ROUND_DOWN);

        if (!OrderState.TO_BE_RECEIVED.getCode().equals(order.getStatus())) {
            return new Result<>().fail(1,"仅待收货订单可确认收货");
        }
        order.setStatus(OrderState.RECEIVED.getCode());
        order.setDisappear(userDisappear);
        //把地址放入order的字段中
        AddrsVo orderAddr = addrsService.getVoById(order.getAddrId());
        order.setAddrString(orderAddr.getContactName() + "&-fw-&" +
                orderAddr.getContactPhone() + "&-fw-&" +
                orderAddr.getProvinceName() +
                orderAddr.getAreaName() +
                orderAddr.getCityName() +
                orderAddr.getAddrInfo());
        updateById(order);
        //addrsService.removeById(orderAddr.getId());


        /*//是否升级VIP
        identityService.addIdentity(getUser());*/

        //向商户付款(非竞猜商品)
        if (order.getIsQuiz() != 1) {
            String msg = payToShop(order, shop.getId());
            //送消证 商户
            //moneysService.disappearReturnParent(shop.getUserId(), null, shopDisappear, "用户消费商户送消证", null);
            moneysService.shopDisappearReturn(shop,shopDisappear,shopDisappear.toString(),"用户线上消费商户获取消证{}");

            //送消证 用户
            moneysService.disappearReturn(order.getUserId() , userDisappear , "购物送消证");
            //添加消费日志
            logsService.saveLogs(order.getUserId(),order.getUserId(), LogsTypeEnum.MONEY_CONSUMPTION.getTypeName(), LogsModelEnum.ALI_PAY.getModelName(),
                    spu.getTitle() ,order.getTotalPrice().toString());
            if (msg != null) { return new Result<>().fail(1, msg); }
        }
        return success();
    }
}
